package com.atguigu.ggkt.utils;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import org.yaml.snakeyaml.Yaml;

import java.io.IOException;
import java.util.Map;
import java.util.Properties;

public class NacosTool {

    public static void main(String[] args) throws IOException {
        String config = NacosTool.loadConfig("dev", "common-dev.yaml", "DEV_GGKT_GROUP");
        System.out.println(config);
    }

    public static String getPropertyFromDevCommon(String key) throws IOException {
        String config = loadConfig("dev", "common-dev.yaml", "DEV_GGKT_GROUP");
        return getProperty(config, key);
    }

    public static String loadConfig(String namespace, String dataId, String groupId) throws IOException {
        // Nacos 服务器地址
//        String serverAddr = "192.168.50.128:8848"; // 根据实际情况修改
//        String namespace = "dev";
//        // 配置的数据 ID
//        String dataId = "common-dev.yaml";
//        // 配置的组 ID
//        String groupId = "DEV_GGKT_GROUP";

        String serverAddr = String.valueOf(SpringTool.getProperty("spring.cloud.nacos.discovery.server-addr"));

        Properties properties = new Properties();
        properties.put("serverAddr", serverAddr);
        properties.put("namespace", namespace);
        String config = null;
        try {
            // 创建 Nacos 配置服务实例
//            ConfigService configService = ConfigFactory.createConfigService(serverAddr);
            ConfigService configService = NacosFactory.createConfigService(properties);
            // 获取 YAML 配置
            config = configService.getConfig(dataId, groupId, 5000);

        } catch (NacosException e) {
            e.printStackTrace();
        }
        return config;
    }

    // 方法用于从 YAML 提取配置
    public static String getProperty(String yamlContent, String key) {

        Yaml yaml = new Yaml();
        Map<String, Object> yamlMap = yaml.load(yamlContent);

        String[] keys = key.split("\\.");
        int length = keys.length;

        for (int i = 0; i < keys.length; i++) {
            if (yamlMap == null) {
                return null;
            }

            if (i == length - 1) {
                return yamlMap.get(keys[i]).toString();
            }

            yamlMap = (Map<String, Object>) yamlMap.get(keys[i]);
        }
        return null;
    }

}
